package com.outsider.util.music;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.outsider.util.OkHttp3;

import us.codecraft.webmagic.selector.Html;

public class XiamiMusic {
	private static final String SEARCH_URL = "http://api.xiami.com/web?v=2.0&app_key=1&page=1&limit=50&r=search/songs&key=";
    private static final HashMap<String, String> headers = new HashMap<>();
    static{
        headers.put("Host","api.xiami.com");
        headers.put("Referer","http://m.xiami.com/");
    }
	
	public static List<Music> search(String name) {
		List<Music> result = new ArrayList<>();
		OkHttp3 okHttp3 = OkHttp3.getInstance();
		JSONObject json = JSONObject.parseObject(okHttp3.getWithHeader(SEARCH_URL + name,headers));
		if (json.getInteger("state")!=0) return null;
		JSONArray songs=json.getJSONObject("data").getJSONArray("songs");
		for (int i=0;i<songs.size();i++){
			JSONObject song=songs.getJSONObject(i);
			result.add(convertMusic(song));
		}
		return result;
	}

	private static Music convertMusic(JSONObject song) {
		Music music=new Music();
		music.setID(song.getString("song_id"));
		music.setName(song.getString("song_name"));
		music.setAlbum(song.getString("album_name"));
		music.setSinger(song.getString("artist_name")!=null?song.getString("artist_name"):song.getString("singers"));
		music.setAlbumID(song.getString("album_id"));
		music.setSingerID(song.getString("artist_id"));
		music.setSource(Music.SOURCE_XIAMI);
		return music;
	}

	private static final String SINGER_SONGS_URL = "http://api.xiami.com/web?v=2.0&app_key=1&page=1&limit=20&r=artist/hot-songs&id=";
	private static final String SINGER_DETAIL_URL = "http://api.xiami.com/web?v=2.0&app_key=1&page=1&limit=20&_ksTS=1459931285956_21&r=artist/detail&id=";
	public static JSONObject getListBySinger(String singerID) {
		JSONObject result=new JSONObject();
		OkHttp3 okHttp3=OkHttp3.getInstance();
		JSONObject singerDetail=JSONObject.parseObject(okHttp3.getWithHeader(SINGER_DETAIL_URL+singerID, headers));
		result.put("cover_img_url", singerDetail.getJSONObject("data").getString("logo"));
		result.put("title",singerDetail.getJSONObject("data").getString("artist_name"));
		result.put("id", Music.SOURCE_XIAMI+"_singer_"+singerID);
		
		JSONObject songsJson=JSONObject.parseObject(okHttp3.getWithHeader(SINGER_SONGS_URL+singerID, headers));
		JSONArray songs=songsJson.getJSONArray("data");
		List<Music> hotsongList=new ArrayList<>();
		for (int i=0;i<songs.size();i++){
    		JSONObject song=songs.getJSONObject(i); 
    		Music music=convertMusic(song);
    		music.setSingerID(singerID);
    		hotsongList.add(music);
		}
		result.put("tracks", hotsongList);
		result.put("is_mine", 0);
		return result;
	}

	
	private static final String ALBUM_DETAIL_URL="http://api.xiami.com/web?v=2.0&app_key=1&page=1&limit=20&r=album/detail&id=";
	public static JSONObject getListByAlbum(String albumID) {
		JSONObject result=new JSONObject();
		OkHttp3 okHttp3=OkHttp3.getInstance();
		JSONObject json=JSONObject.parseObject(okHttp3.getWithHeader(ALBUM_DETAIL_URL+albumID, headers));
		result.put("cover_img_url", json.getJSONObject("data").getString("album_logo"));
		result.put("title",json.getJSONObject("data").getString("album_name"));
		result.put("id", Music.SOURCE_NETEASE+"_album_"+albumID);
		JSONArray songs=json.getJSONObject("data").getJSONArray("songs");
		List<Music> hotsongList=new ArrayList<>();
		for (int i=0;i<songs.size();i++){
    		JSONObject song=songs.getJSONObject(i); 
    		Music music=convertMusic(song);
    		hotsongList.add(music);
		}
		result.put("tracks", hotsongList);
		result.put("is_mine", 0);
		return result;
	}
    
	public static String getURL(String ID) {
		String jsonUrl = "http://www.xiami.com/song/playlist/id/" + ID + "/object_id/0/cat/json";
		OkHttp3 okHttp3 = OkHttp3.getInstance();
		String content = okHttp3.get(jsonUrl);

		JSONObject json = JSONObject.parseObject(content);
		if (null == json || json.getBoolean("status") == false)
			return null;
		JSONObject data = json.getJSONObject("data");
		JSONArray trackList = data.getJSONArray("trackList");
		JSONObject track = trackList.getJSONObject(0);
		try {
			return decode((String) track.get("location"));
		} catch (UnsupportedEncodingException e) {
			return null;
		}
	}

	private static String decode(String location) throws UnsupportedEncodingException {
		int _local10;
		int _local2 = Integer.parseInt(location.substring(0, 1));
		String _local3 = location.substring(1, location.length());
		double _local4 = Math.floor(_local3.length() / _local2);
		int _local5 = _local3.length() % _local2;
		String[] _local6 = new String[_local2];
		int _local7 = 0;
		while (_local7 < _local5) {
			if (_local6[_local7] == null) {
				_local6[_local7] = "";
			}
			_local6[_local7] = _local3.substring((((int) _local4 + 1) * _local7),
					(((int) _local4 + 1) * _local7) + ((int) _local4 + 1));
			_local7++;
		}
		_local7 = _local5;
		while (_local7 < _local2) {
			_local6[_local7] = _local3.substring(
					(((int) _local4 * (_local7 - _local5)) + (((int) _local4 + 1) * _local5)),
					(((int) _local4 * (_local7 - _local5)) + (((int) _local4 + 1) * _local5)) + (int) _local4);
			_local7++;
		}
		String _local8 = "";
		_local7 = 0;
		while (_local7 < ((String) _local6[0]).length()) {
			_local10 = 0;
			while (_local10 < _local6.length) {
				if (_local7 >= _local6[_local10].length()) {
					break;
				}
				_local8 = (_local8 + _local6[_local10].charAt(_local7));
				_local10++;
			}
			_local7++;
		}
		_local8 = URLDecoder.decode(_local8, "utf8");
		String _local9 = "";
		_local7 = 0;
		while (_local7 < _local8.length()) {
			if (_local8.charAt(_local7) == '^') {
				_local9 = (_local9 + "0");
			} else {
				_local9 = (_local9 + _local8.charAt(_local7));
			}
			;
			_local7++;
		}
		_local9 = _local9.replace("+", " ");
		return _local9;
	}
	public static void main(String[] args) {
		XiamiMusic.search("锦鲤抄");
	}


}
